package com.atzxh.heima.netty.c3;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;

/**
 * @author 小红同学
 * @date 2023-12-18-21:17
 * @description
 */
@Slf4j
public class TestNettyPromise {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        EventLoop eventLoop = new NioEventLoopGroup().next();
        // 主动创建结果容器--> promise
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);
        new Thread(()->{
            log.debug("执行计算");
            try {
                int i = 1 / 0;
                Thread.sleep(1000);
                promise.setSuccess(80);
            } catch (InterruptedException e) {
                e.printStackTrace();
                // 异常处理
                promise.setFailure(e);
            }
        }).start();
        // 同步获取结果
        log.debug("等待结果");
        log.debug("结果为：{}",promise.get());

        // 异步获取
//        promise.addListener(new GenericFutureListener<Future<? super Integer>>() {
//            @Override
//            public void operationComplete(Future<? super Integer> future) throws Exception {
//                log.debug("结果为：{}",promise.get());
//            }
//        });
    }
}
